<template>
  <basic-modal
    v-bind="$attrs"
    show-confirm
    :title="modalTitle"
    :confirm-loading="confirmLoading"
    @confirm="handleSubmit"
  >
    <n-form ref="formRef" :model="modelForm" :rules="rules">
      <n-form-item label="品牌名称" path="name">
        <n-input placeholder="请输入品牌名称" v-model:value="modelForm.name" />
      </n-form-item>
      <n-form-item label="状态" path="status">
        <n-select
          v-model:value="modelForm.status"
          :options="STATUS_LIST"
          placeholder="请选择状态"
        />
      </n-form-item>
      <n-form-item label="排序" path="sort">
        <n-input-number
          class="w-full"
          clearable
          placeholder="请输入排序"
          v-model:value="modelForm.sort"
        />
      </n-form-item>
      <n-form-item label="图标" path="image">
        <n-upload
          response-type="json"
          :max="1"
          :headers="headers"
          :action="`${uploadUrl}?biz=brands`"
          v-model:file-list="fileList"
          list-type="image-card"
          @finish="handleUploadFinish"
          @remove="handleUploadRemove"
        >
          点击上传
        </n-upload>
      </n-form-item>
      <n-form-item label="描述" path="remark">
        <n-input
          placeholder="请输入描述"
          type="textarea"
          v-model:value="modelForm.remark"
        />
      </n-form-item>
    </n-form>
  </basic-modal>
</template>
<script setup lang="ts">
import { FormInst, UploadFileInfo, useMessage } from "naive-ui";
import { ref, reactive, computed, watch, useAttrs } from "vue";
import { get, isEmpty } from "lodash-es";
import BasicModal from "@/components/normal/basicModal/index.vue";
import { getHeaders } from "@/common/utils/comps/index";
import { uploadUrl } from "@/api/basic/basic.api";
import { addBrand, editBrand } from "@/api/product/brand.api";
import { IBrandModalProps } from "./props";
import { ActionTypeEnum } from "@/enums/actionTypeEnum";
import { DictStorage } from "@/storage/dict.storage";

const rules = {
  name: [
    {
      required: true,
      message: "请输入产品分类名称",
      trigger: "change",
    },
  ],
  status: [
    {
      required: true,
      message: "请选择状态",
      trigger: "change",
    },
  ],
};

const STATUS_LIST = DictStorage.getDictItemsByCode("pos_category_status");

const emits = defineEmits(["createSuccess", "editSuccess"]);

const $attrs = useAttrs();
const message = useMessage();
const headers = getHeaders();

const props = withDefaults(defineProps<IBrandModalProps>(), {
  actionType: ActionTypeEnum.ADD,
});

const confirmLoading = ref<boolean>(false);
const formRef = ref<FormInst | null>(null);
const fileList = ref<UploadFileInfo[]>([]);

const modelForm = reactive({
  id: "",
  name: "",
  status: undefined,
  image: "",
  sort: 0,
  remark: "",
});

const modalTitle = computed(() => {
  const _actionType = get(props, "actionType");
  if (_actionType === ActionTypeEnum.ADD) {
    return "新增品牌";
  } else if (_actionType === ActionTypeEnum.EDIT) {
    return "编辑品牌";
  } else {
    return "";
  }
});

watch(
  () => props.formData,
  (newVal) => {
    if (!isEmpty(newVal)) {
      initEditForm(newVal);
    }
  }
);

watch(
  () => $attrs.show,
  (newVal) => {
    if (!newVal) {
      setTimeout(() => {
        modelForm.name = "";
        modelForm.id = "";
        modelForm.status = undefined;
        modelForm.remark = "";
        modelForm.sort = 0;
        modelForm.image = "";
      }, 200);
    }
  }
);

const initEditForm = (newVal: any) => {
  modelForm.id = newVal.id;
  modelForm.name = newVal.name;
  modelForm.status = newVal.status;
  modelForm.sort = newVal.sort;
  modelForm.remark = newVal.remark;
};

const handleUploadFinish = (payload: any) => {
  console.log(payload);
  const url = get(payload, "event.target.response.message") || "";
  if (url) {
    modelForm.image = url;
  }
};

const handleUploadRemove = (payload: any) => {
  console.log(payload);
  modelForm.image = "";
};

const handleAddBrand = async () => {
  try {
    confirmLoading.value = true;
    await addBrand(modelForm);
    emits("createSuccess");
  } finally {
    confirmLoading.value = false;
  }
};

const handleEditBrand = async () => {
  try {
    confirmLoading.value = true;
    await editBrand(modelForm);
    emits("editSuccess");
  } finally {
    confirmLoading.value = false;
  }
};

const handleSubmit = async () => {
  formRef.value?.validate(async (errors) => {
    if (errors) {
      message.error("请正确输入表单项");
      return;
    }
    if (props.actionType === ActionTypeEnum.ADD) {
      await handleAddBrand();
    } else if (props.actionType === ActionTypeEnum.EDIT) {
      await handleEditBrand();
    }
  });
};
</script>
